const http = require("http");
const fs = require("fs");
const path = require("path");
// 监听的过程也是一个异步的处理,只有收到http请求的时候才执行
var pagePath = path.join(__dirname, "/index.html");
var iconPath = path.join(__dirname, "/icon.png");
var dirPath = path.join(__dirname, "/fileDir");

function judge(a) {
    if (a < 10) {
        return "0" + a;
    } else {
        return a;
    }
}

function format(t) {
    var d = new Date(t);
    var y = d.getFullYear();
    var m = d.getMonth() + 1;
    var s = d.getDate();
    return y + "-" + judge(m) + "-" + judge(s);
}

// 转换url
function parseUrl(urlStr) {
    var index = urlStr.indexOf("?");
    var pathname = "";
    var args = "";
    var argObj = {};
    // http://localhost:8081/pathname?delId=23234&pageId=10
    if (index !== -1) {
        pathname = urlStr.slice(0, index);
        args = urlStr.slice(index + 1);
        // console.log(args);
        var argArr = args.split("&");
        // console.log(argArr);
        for (var i = 0; i < argArr.length; i++) {
            argObj[argArr[i].split("=")[0]] = argArr[i].split("=")[1];
        }
    } else {
        pathname = urlStr;
    }
    return {
        pathname: pathname,
        argObj: argObj,
    };
}

function router(urlObj, req, res) {
    if (
        urlObj.pathname.indexOf(".png") > 0 ||
        urlObj.pathname.indexOf(".jpg") > 0
    ) {
        urlObj.pathname = "getimgdata";
    }
    switch (urlObj.pathname) {
        case "/":
            showIndex(res);
            break;
        case "getimgdata":
            resImg(res);
            break;
        case "/getlist":
            showList(res);
            break;
        case "/del":
            deleteList(urlObj.argObj, res);
            break;
    }
}
function showIndex(res) {
    var fileContent = fs.readFileSync(pagePath);
    res.writeHead(200, { "Content-Type": "text/html" });
    res.write(fileContent);
    res.end();
}
function resImg(res) {
    var imgContent = fs.readFileSync(iconPath);
    res.writeHead(200, { "Content-Type": "image/png" });
    res.write(imgContent);
    res.end();
}
function showList(res) {
    var arr = [];
    var dir = fs.readdirSync(dirPath);
    for (var i = 0; i < dir.length; i++) {
        var obj = {};
        var file = path.join(dirPath, dir[i]);
        var stat = fs.statSync(file);
        if (stat.isDirectory()) {
            obj.fileType = "folder";
        } else if (stat.isFile()) {
            obj.fileType = "file";
        }
        obj.fileName = dir[i].split(".")[0] || "";
        obj.fileSize = stat.size;
        obj.fileTime = format(stat.ctimeMs);
        arr.push(obj);
    }
    var jsonString = JSON.stringify(arr);
    res.writeHead(200, { "Content-Type": "text/plain;charset=utf-8" });
    res.write(jsonString);
    res.end();
}

function deleteFile(p) {
    var stat = fs.statSync(p);
    if (stat.isFile()) {
        fs.unlinkSync(p);
    } else if (stat.isDirectory()) {
        var f = fs.readdirSync(p);
        for (var i = 0; i < f.length; i++) {
            var f1 = path.join(p, f[i]);
            deleteFile(f1);
        }
        fs.rmdirSync(p);
    }
}

function deleteList(argObj, res) {
    console.log(argObj);
    var delId = argObj.delId;
    var dirp = path.join(__dirname, "/fileDir");
    var files = fs.readdirSync(dirp);
    for (var i = 0; i < files.length; i++) {
        var p = path.join(dirp, files[i]);
        var fileObj = fs.statSync(p);
        if (delId.indexOf(format(fileObj.ctimeMs)) > 0) {
            console.log("success");
            deleteFile(p);
            res.end("success");
            break;
        }
    }
}
http.createServer((req, res) => {
    /**
     * 完整的一个url
     * http://localhost:8081/pathname?delId=23234&pageId=10
     * 回调函数中要解析这个url
     *
     * req.url指端口或者域名之后的部分
     */
    var urlstr = req.url;
    console.log(urlstr);
    var urlObj = parseUrl(urlstr);
    console.log(urlObj);
    router(urlObj, req, res);
}).listen(8081);
console.log("server listening on");
